package com.alibaba.sdk.config.async;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * executor工厂
 *
 * @ author  Shawn(Shawn_0217@163.com)
 * @ date    2021/4/27 15:27
 * @ company Alibaba
 */
public final class ExecutorFactory {

    public static ThreadPoolTaskExecutor createPoolTaskExecutor(ThreadPoolConfig config) {
        // 处理器时间
        int processorCount = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = config.getMaxPoolSize() <= 0 ? processorCount : config.getMaxPoolSize();
        int corePoolSize = config.getCorePoolSize() <= 0 ? processorCount : config.getCorePoolSize();

        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setKeepAliveSeconds(config.getKeepAliveSeconds());
        taskExecutor.setQueueCapacity(config.getQueueCapacity());
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 初始化
        taskExecutor.initialize();
        return taskExecutor;
    }
}
